package com.demo.handler;

import com.alibaba.fastjson2.JSONObject;
import com.demo.model.AuthConstants;
import com.demo.model.ResultMsg;
import com.demo.model.SecurityUser;
import com.demo.utils.JWTUtil;
import com.demo.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        // 获取登录用户信息
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        // 生成令牌 token
        String jwt_token = JWTUtil.createJWT(JSONObject.toJSONString(securityUser));
        // 将 token 存放到 redis 中
        redisTemplate.opsForValue().set(AuthConstants.TOKEN_PREFIX + jwt_token,"", Duration.ofMinutes(60*12));
        // 响应 token 令牌给前端
        ResponseUtil.writeJson(response, ResultMsg.OK(jwt_token));
//        ResponseUtil.writeJson(response, ResultMsg.OK(CodeEnum.OPERATION_FAIL));
    }
}
